package dhz.storage.filter;

import dhz.storage.util.JwtToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtFilter extends BasicHttpAuthenticationFilter {
    static final Logger logger = LoggerFactory.getLogger(BasicHttpAuthenticationFilter.class);
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse res= (HttpServletResponse) response;
        res.setHeader("Access-control-Allow-Origin",req.getHeader("Origin"));
        res.setHeader("Access-control-Allow-Methods","GET,POST,OPTIONS,PUT,DELETE");
        res.setHeader("Access-control-Allow-Headers",req.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            res.setStatus(200);
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue){
        if(isLoginAttempt(request, response)){
            try{
                boolean status = executeLogin(request, response);
                if(!status){
                    ((HttpServletResponse)response).sendRedirect("/util/unauthorized");
                    return false;
                }
                return true;
            }catch(Exception e){
                return false;
            }
        }else{
            return false;
        }
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");
        if(token == null){
            logger.warn("login attempt blocked");
            return false;
        }else{
            return true;
        }
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response)throws Exception{
        try{
            JwtToken token = new JwtToken(((HttpServletRequest)request).getHeader("Authorization"));
            getSubject(request, response).login(token);
        }
        catch(Exception e){
            logger.error(((HttpServletRequest)request).getHeader("Authorization")+" verification failed!");
            return false;
        }
        return true;
    }
}
